//Cache the real active tab for the whole browser
var activeTab;

chrome.tabs.query({active:true}, function(tabArray){
	if(tabArray.length > 0){
		activeTab = tabArray[0];
	}
});

var windows = {
	/**
	* get all Tabs from browser
	*
	* @return {list} all tabs.
	*/
	getAllTabs: function (callback) {
		chrome.windows.getAll({"populate" : true}, function (all_windows) {
			var all_tabs = [];
			for(var i=0;i<all_windows.length;i++) {
				all_tabs = all_tabs.concat(all_windows[i].tabs);
			}
			if(callback){
				callback(all_tabs);
			}
		});
	},

	/**
	* get all Windows from browser
	*
	* @return {list} all windows.
	*/
	getAllWindows: function (callback) {
		chrome.windows.getAll({"populate" : true}, function (all_windows) {
			if(callback){
				callback(all_windows);
			}
		});
	},

	/**
	* delete windows by ids
	*
	*/
	deleteWindows: function (ids) {
		if(ids != null){
			for(var i=0;i<ids.length;i++) {
				//var windowId = ids[i];
				chrome.windows.remove(ids[i], function () {});
			}
		}
	}
}

// init all tabs
var initTabs = function(windowTTId, all_tabs){

	for(var i=0;i<all_tabs.length;i++) {
		var newRow = "<tr data-tt-id='%parentId%.%id%' data-tt-parent-id='%parentId%'>" +
			"<td><span hidden='hidden'>%tabId%</span><span style='background:url(%favIconUrl%);background-position: center left;background-repeat: no-repeat;padding: .2em 0 .2em 1.5em;background-size: 16px 16px;'>%title%</span></td></tr>";
		var favIconUrl = all_tabs[i].favIconUrl;
		if(!favIconUrl){
			favIconUrl = "no_favIcon.jpg";
		}
		
		var replacements = {
			'%parentId%': windowTTId,
			'%id%': i+1,
			'%tabId%': all_tabs[i].id,
			'%favIconUrl%': favIconUrl,
			'%title%': all_tabs[i].title
			//'%url%': all_tabs[i].url
		};

		$("#tabs-group-table tbody").append(newRow.replace(/%\w+%/g, function(all) {
			return replacements[all] || all;
		}));
	}
}

//Select a tab
var selectTab = function(tabId){
	try{
		chrome.tabs.update(parseInt(tabId), {active:true}, function(tab){
			chrome.windows.update(tab.windowId, {focused:true}, function(){})
		});
	}catch(ex){
		console.error('Tab does not exist for id ' + tabId, ex);
	}
}

// Run initialization script as soon as the document's DOM is ready.
document.addEventListener('DOMContentLoaded', function () {
	
	windows.getAllWindows(function(all_windows) {

		var all_tabs = [];
		// init the group and tabs tree for browser
		for(var i=0;i<all_windows.length;i++) {
			var tt_id = all_windows[i].id;
			//if(tt_id <= 0){
				//	tt_id = 1;
				//}
				// add a new group node
				var newRow = "<tr data-tt-id='%id%'><td><span class='folder'>Default Group %id%</span>" + 
					"<span _id='%id%' class='delete'></span></td></tr>";
				var replacements = {
					'%id%': tt_id
				};

				$("#tabs-group-table tbody").append(newRow.replace(/%\w+%/g, function(all) {
					return replacements[all] || all;
				}));

				// add tabs node
				initTabs(tt_id,all_windows[i].tabs);;
		}

		// init tree table
		$("#tabs-group-table").treetable({ expandable: true });

		// Highlight selected row
		$("#tabs-group-table tbody").on("mousedown", "tr", function() {
			$(".selected").not(this).removeClass("selected");
			$(this).toggleClass("selected");
		});

		// Dwell action for selected row
		$("#tabs-group-table tbody").on("mouseover", "tr", function(){
			var tabId = $(this).find("span[hidden='hidden']").text();
			if(tabId != ""){
				selectTab(tabId);
			}
		});
		
		// Change back the active tab
		$("#tabs-group-table tbody").on("mouseleave", "tr", function(){
			if(activeTab){
				selectTab(activeTab.id);
			}
		});

		// enable Drag & Drop feature on table
		//	enableDragDrop();

		// expand all node
		$('#tabs-group-table').treetable('expandAll');
		/*
		// add delete group button click event
		$(".delete").click(function(){
		var strValue = $(this).attr('_id');
		var intValue = parseInt(strValue);
		windows.deleteWindows([intValue])
		$(this).parents("tr").remove();
		return false;
		})
		*/

	});
});

